<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>案例_地区查询</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
  <style>
    :root {
      font-size: 15px;
    }

    body {
      padding-top: 15px;
    }
  </style>
</head>

<body>
  <a href="./04.searchParams.html?id=123&name=jack">searchParams</a>
  <div class="container">
    <form id="editForm" class="row">
      <!-- 输入省份名字 -->
      <div class="mb-3 col">
        <label class="form-label">省份名字</label>
        <input type="text" value="北京" name="province" class="form-control province" placeholder="请输入省份名称" />
      </div>
      <!-- 输入城市名字 -->
      <div class="mb-3 col">
        <label class="form-label">城市名字</label>
        <input type="text" value="北京市" name="city" class="form-control city" placeholder="请输入城市名称" />
      </div>
    </form>
    <button type="button" class="btn btn-primary sel-btn">查询</button>
    <br><br>
    <p>地区列表: </p>
    <ul class="list-group area-group">
      <!-- 示例地区 -->
      <li class="list-group-item">东城区</li>
    </ul>
  </div>


  <script>
    /* 步骤分析
    1、点击查询按钮
    2、获取表单值
    3、创建 XMLHttpRequest 对象 发送请求
    4、需要传递两个参数
    */
    //  1、点击查询按钮
    document.querySelector('.sel-btn').addEventListener('click', () => {
      //  2、获取表单值
      const province = document.querySelector('.province').value
      const city = document.querySelector('.city').value
      /* 4、URLSearchParams 参数处理 */
      const data = new URLSearchParams({
        pname: province,
        cname: city
      })
      console.log(data.toString(), 222); // data.toString() ===pname=${province}&cname=${city}
      //  3、创建 XMLHttpRequest 对象 发送请求
      const xhr = new XMLHttpRequest()
      // xhr.open('get', `http://hmajax.itheima.net/api/area?pname=${province}&cname=${city}`)
      xhr.open('get', `http://hmajax.itheima.net/api/area?${data.toString()}`)
      xhr.addEventListener('loadend', () => {
        console.log(xhr.response);
      })
      xhr.send()
    })
  </script>

</body>

</html>